<template>
  <div id="qiRptFiled">
    <Splitpanes>
      <Pane size="25">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" :loading="showLoading" @click="findqiIndexIMainList()"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-square-plus" class="button-blue" content="新增" @click="handleAdd(-1)"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="qiRptFiledTable">
          <vxe-table ref="qiRptFiledTableRef" :loading="showLoading" class="mytable-scrollbar" align="left" border height="auto" :keep-source="true" :data="qiIndexIMainList" @current-change="qiIndexItemRowClick" :row-config="{ isCurrent: true, isHover: true }" resizable show-overflow>
            <vxe-column type="checkbox" align="center" width="26"></vxe-column>
            <vxe-column field="seq" title="顺序" width="50px" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.seq" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="itemCode" title="项目编码" width="80px" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.itemCode" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="itemName" title="项目名称" min-width="200px" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.itemName" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="itemGroup" title="项目分组" min-width="100px" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.itemGroup" type="text"></vxe-input>
              </template>
            </vxe-column>

          </vxe-table>
        </div>
      </Pane>
      <Pane size="75">
        <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick" class="elTabs">
          <el-tab-pane label="基本信息" name="first">
            <el-form ref="qiIndexItemFormRef" :model="qiIndexItemForm" :rules="qiIndexItemFormRule" label-width="100px" inline-message>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item prop="itemCode" label="项目编码">
                    <el-input type="text" v-model="qiIndexItemForm.itemCode" placeholder="请输入项目编码" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item prop="itemName" label="项目名称">
                    <el-input type="text" v-model="qiIndexItemForm.itemName" placeholder="请输入项目名称" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item prop="itemGroup" label="项目分组">
                    <el-input type="text" v-model="qiIndexItemForm.itemGroup" placeholder="请输入项目名称" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="是否启用" prop="enable">
                    <el-switch v-model="qiIndexItemForm.enable" inline-prompt active-text="是" inactive-text="否"></el-switch>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="统计类型" prop="orgId">
                    <el-select v-model="qiIndexItemForm.statType" placeholder="请选择" style="width:200px">
                      <el-option v-for="item in statTypeList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="qiIndexItemForm.remark" placeholder="请输入备注" clearable type="textarea"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item prop="seq" label="顺序">
                    <el-input-number v-model="qiIndexItemForm.seq" :min="1" :max="1000" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item class="form-footer">
                    <template #default>
                      <el-button type="primary" @click="saveQiIndexItem('qiIndexItemFormRef')">保存</el-button>
                    </template>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
          </el-tab-pane>
          <el-tab-pane label="固定值" name="third" v-if="qiIndexItemForm.statType=='3'" :disabled="IsEmpty(slQiItem)">
            <QiIndexItemFixed ref="qiIndexItemFixedRef" />
          </el-tab-pane>
          <el-tab-pane label="数据接口配置" name="second" :disabled="IsEmpty(slQiItem)">
            <QiIndexItemSet ref="qiIndexItemSetRef" />
          </el-tab-pane>
        </el-tabs>
      </Pane>
    </Splitpanes>

  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, defineExpose } from 'vue';
import { IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { Splitpanes, Pane } from 'splitpanes';
import QiIndexItemSet from './QiIndexItemSet.vue';
import QiIndexItemFixed from './QiIndexItemFixed.vue';
import { AppStore } from '@/stores/store'; //'../../../stores/store';

let store = AppStore();

// 全局变量定义区 ==========
defineExpose({
  initPage
});

interface RowVO {
  id: string;
  itemCode: string;
  itemName: string;
  seq: number; //顺序号
  indexId: string;
  qidxId: string;
}

let { proxy }: any = getCurrentInstance();
let showLoading = ref(false); //刷新+表格加载状态
const qiIndexIMainList = reactive([]);
let qiIndex: any = null;

const qiRptFiledTableRef = ref(null);
let slQiItem: any = ref({});
let activeName = ref('first');
let qiIndexItemSetRef: any = ref(null);
let qiIndexItemFixedRef: any = ref(null);
// 右侧基本信息表单
let qiIndexItemForm = reactive({
  id: null,
  indexId: '',
  itemCode: '',
  itemName: '',
  itemGroup: '',
  enable: true,
  statType: '1',
  remark: '',
  seq: 1,
  orgId: ''
});

let qiIndexItemFormRule = {
  itemCode: [
    {
      required: true,
      message: '请输入项目编码',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};
let statTypeList: any = reactive([]);
// 方法定义区 =============
onMounted(() => {
  getDictItemsList(); //批量获取字典
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['qiStatType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const faultGrades = dictTreeTypeItems.data.find((item: any) => item.code === 'qiStatType');
  statTypeList.push(...faultGrades.detailDataList);
}

function initPage(row: any) {
  qiIndex = row;
  findqiIndexIMainList();
}
// 获取列表
function findqiIndexIMainList() {
  showLoading.value = true;
  qiIndexIMainList.length = 0; //放入数据前清空数据
  const url = '/api/qi/reportFiled/getQiIndexItemList/' + qiIndex.indexCode;
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.status.code === 1) {
        qiIndexIMainList.push(...res.data);
        showLoading.value = false;
        const kn = qiIndexIMainList.find((k: any) => k.id == slQiItem.value.id);
        if (IsEmpty(kn)) {
          qiIndexItemRowClick({ row: qiIndexIMainList[0] }); //默认选中第一条数据
        } else {
          qiIndexItemRowClick({ row: kn }); //默认选中第一条数据
        }
      } else {
        showLoading.value = false;
        VxeMessage('获取列表失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      showLoading.value = false;
    });
}

// 点击表格当前行
function qiIndexItemRowClick({ row }: any) {
  if (IsEmpty(row)) {
    //slQiItem.value = {};
    clearForm();
    activeName.value = 'first';
  } else {
    (proxy.$refs.qiRptFiledTableRef as any).setCurrentRow(row);
    //slQiItem.value = row;
    setQiItemForm(row);
    if (activeName.value == 'second') {
      qiIndexItemSetRef.value.initPage(row, qiIndex);
    } else if (row.statType == '3' && activeName.value == 'third') {
      qiIndexItemFixedRef.value.initPage(row, qiIndex);
    } else {
      activeName.value = 'first';
    }
  }
}
function clearForm() {
  qiIndexItemForm.id = null;
  qiIndexItemForm.indexId = '';
  qiIndexItemForm.enable = true;
  qiIndexItemForm.remark = '';
  qiIndexItemForm.itemCode = '';
  qiIndexItemForm.itemName = '';
  qiIndexItemForm.statType = '1';
  qiIndexItemForm.itemGroup = '';
  qiIndexItemForm.orgId = '';
  qiIndexItemForm.seq = qiIndexIMainList.length + 1;
  slQiItem.value = {};
}

function setQiItemForm(row: any) {
  qiIndexItemForm.id = row.id;
  qiIndexItemForm.indexId = row.indexId;
  qiIndexItemForm.enable = row.enable;
  qiIndexItemForm.remark = row.remark;
  qiIndexItemForm.itemCode = row.itemCode;
  qiIndexItemForm.itemName = row.itemName;
  qiIndexItemForm.statType = row.statType;
  qiIndexItemForm.itemGroup = row.itemGroup;
  qiIndexItemForm.orgId = row.orgId;
  qiIndexItemForm.seq = row.seq;
  slQiItem.value = row;
}

//新增
async function handleAdd(row?: RowVO | number) {
  (proxy.$refs.qiRptFiledTableRef as any).clearCurrentRow();
  activeName.value = 'first';
  clearForm();
}

//删除
function handleDelete() {
  const $xTable = proxy.$refs.qiRptFiledTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        selectRows.forEach((item, idx) => {
          const url = '/api/qi/reportFiled/deleteQiIndexItem';
          proxy.$http
            .post(url, item)
            .then((res: any) => {
              if (idx === selectRows.length - 1) {
                VxeMessage('删除成功', VxeNotifyType.success);
                findqiIndexIMainList();
              }
            })
            .catch((err) => {
              VxeMessage('删除时出现异常', VxeNotifyType.error);
            });
        });
      }
    });
}

function saveQiIndexItem(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (qiIndexItemForm.id === null) {
      const url = '/api/qi/reportFiled/addQiIndexItem';
      const supplier = {
        indexId: qiIndex.id,
        indexCode: qiIndex.indexCode,
        enable: qiIndexItemForm.enable,
        remark: qiIndexItemForm.remark,
        itemCode: qiIndexItemForm.itemCode,
        itemName: qiIndexItemForm.itemName,
        statType: qiIndexItemForm.statType,
        itemGroup: qiIndexItemForm.itemGroup,
        seq: qiIndexItemForm.seq,
        orgId: store.userInfo.orgId
      };
      proxy.$http
        .post(url, supplier)
        .then((res: any) => {
          VxeMessage('新增成功', VxeNotifyType.success);
          slQiItem.value.id = res.data.id;
          findqiIndexIMainList();
        })
        .catch((err: any) => {
          console.log(err);

          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/qi/reportFiled/updateQiIndexItem';
      const supplier = {
        id: qiIndexItemForm.id,
        indexId: qiIndexItemForm.indexId,
        enable: qiIndexItemForm.enable,
        remark: qiIndexItemForm.remark,
        itemCode: qiIndexItemForm.itemCode,
        itemName: qiIndexItemForm.itemName,
        statType: qiIndexItemForm.statType,
        itemGroup: qiIndexItemForm.itemGroup,
        seq: qiIndexItemForm.seq,
        orgId: qiIndexItemForm.orgId
      };
      proxy.$http
        .post(url, supplier)
        .then((res: any) => {
          VxeMessage('修改成功', VxeNotifyType.success);
          slQiItem.value.id = res.data.id;
          setTimeout(() => {
            findqiIndexIMainList();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.error);
        });
    }
  });
}

function tabHandleClick(tab: any) {
  console.log(tab.props.name);

  if (tab.props.name == 'second') {
    qiIndexItemSetRef.value.initPage(slQiItem.value, qiIndex);
  }
  if (tab.props.name == 'third') {
    qiIndexItemFixedRef.value.initPage(slQiItem.value, qiIndex);
  }
}
</script>

<style lang="scss" scoped>
#qiRptFiled {
  height: 100%;
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
  .qiRptFiledTable {
    height: calc(100% - 40px);
  }
  .elTabs {
    height: 100%;
    :deep(.el-tabs__content) {
      height: calc(100% - 39px);
      padding: 0;
      .el-tab-pane {
        padding: 0;
        height: 100%;
      }
      #pane-first {
        padding: 15px;
        height: calc(100% - 30px);
      }
    }
  }
}
</style>
